import { defineStore } from 'pinia';
import { LoginRequest, userLogin, refresUserInfo } from '@/api/user';
import pinia from '@/store';
import { IUserState } from './type';
export const useUserStoreHook = defineStore('userInfo', {
  state: (): IUserState => ({
    username: 'ange',
    accessToken: '',
    refreshToken: '',
    roles: ['amdin']
  }),
  getters: {
    userName(): string {
      return this.username;
    }
  },
  actions: {
    async storeUserLogin(data: LoginRequest) {
      const res = await userLogin(data);
      this.accessToken = res.data.accessToken;
      this.username = res.data.username;
      this.roles = res.data.roles;
      return res.data;
    },
    // sotreRefreshUserInfo() {
    //   if (this.username == 'ange' && this.accessToken != '') {
    //     refresUserInfo()
    //       .then((res) => {
    //         this.username = res.username;
    //         this.roles = res.roles;
    //         this.accessToken = res.accessToken;
    //       })
    //       .catch(() => {
    //         this.accessToken = '';
    //       });
    //   }
    // },
    storeLogout() {
      const router = useRouter();
      console.log(router);
      sessionStorage.removeItem('userInfo');
    }
  },
  persist: {
    key: 'userInfo',
    storage: sessionStorage,
    pick: ['username', 'accessToken']
  }
});

export default function useUserStore() {
  return useUserStoreHook(pinia);
}
